import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { verifyToken } from '@/app/lib/auth';
import prisma from '@/app/lib/prisma';
import { DietRecommendation } from '@prisma/client';

interface FormattedRecommendation extends Omit<DietRecommendation, 'macronutrients' | 'mealPlan' | 'tips'> {
  macronutrients: {
    protein: number;
    carbs: number;
    fat: number;
  };
  mealPlan: {
    breakfast: string[];
    lunch: string[];
    dinner: string[];
    snacks: string[];
  };
  tips: string[];
}

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const recommendations = await prisma.dietRecommendation.findMany({
      where: { userId: payload.userId },
      orderBy: { createdAt: 'desc' },
      take: 5, // 只获取最近5条记录
    });

    // 解析 JSON 字符串
    const formattedRecommendations: FormattedRecommendation[] = recommendations.map(rec => ({
      ...rec,
      macronutrients: JSON.parse(rec.macronutrients),
      mealPlan: JSON.parse(rec.mealPlan),
      tips: JSON.parse(rec.tips),
    }));

    return NextResponse.json({ recommendations: formattedRecommendations });
  } catch (error) {
    console.error('获取饮食推荐历史错误:', error);
    return NextResponse.json(
      { message: '获取饮食推荐历史失败' },
      { status: 500 }
    );
  }
} 